<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type");

// 读取用户数据
$userDataDir = 'data/users.json';
$orderDataDir = "data/orders.json";
$userData = json_decode(file_get_contents($userDataDir), true);
$orderData = json_decode(file_get_contents($orderDataDir), true);

// 接收 POST 请求
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 检查用户是否登录
    if (isset($_POST['username']) && isset($_POST['password'])) {
        $username = $_POST['username'];
        $password = $_POST['password'];

        // 检查用户名和密码
        if (checkCredentials($userData, $username, $password)) {
            // 处理下单
            if (isset($_POST['order_content'])) {
                $orderContent = $_POST['order_content'];
                $timestamp = time();
                $orderNumber = generateOrderNumber($timestamp);
                $orderTime = date('Y-m-d H:i:s', $timestamp);

                // 添加订单信息
                $newOrder = array(
                    'order_number' => $orderNumber,
                    'username' => $username,
                    'order_content' => json_decode($orderContent, true),
                    'order_time' => $orderTime
                );

                $orderData['orders'][] = $newOrder;

                // 更新用户数据文件
                file_put_contents($orderDataDir, json_encode($orderData));

                echo json_encode(array('status' => 200, 'message' => 'Order placed successfully.', 'order_number' => $orderNumber));
            } else {
                echo json_encode(array('status' => 500, 'message' => 'Order content is missing.'));
            }
        } else {
            echo json_encode(array('status' => 500, 'message' => 'Invalid username or password.'));
        }
    } else {
        echo json_encode(array('status' => 500, 'message' => 'Username or password is missing.'));
    }
}

// 检查用户名和密码
function checkCredentials($userData, $username, $password)
{
    foreach ($userData['users'] as $user) {
        if ($user['username'] === $username && password_verify($password, $user['password'])) {
            return true;
        }
    }
    return false;
}

// 生成订单号
function generateOrderNumber($timestamp)
{
    return 'ORD' . $timestamp; // 这只是一个简单的生成订单号的方法，实际项目中可能需要更复杂的实现。
}
?>
